package cn.lhy.tools;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Iterator;

public class PDF2ImgUtils {
    public final  static String  IMG_TYPE_JPG = "jpg";
    public final  static String  IMG_TYPE_PNG = "png";

    public static void main(String[] args) {
        Long time = System.currentTimeMillis();
        Integer integer = PDF2Img("D:\\2.pdf", "/2000/1/2", IMG_TYPE_JPG,0, false);
        System.out.println(integer);
        Long time1 = System.currentTimeMillis();
        System.out.println("耗时："+(time1-time)/1000+"s");
    }

    /**
     *  将pdf拆装成图片，图片名称默认为pdf下标
     * @param filePath pdf 路径
     * @param saveFile  保存路径
     * @param imgType   图片类型
     * @param start 起始页码
     * @return  返回最后结束页码
     * @throws IOException
     */
    public static Integer PDF2Img(String filePath,String saveFile,String imgType,Integer start){
        if(null==start){
            start = 0;
        }
        return isFtpModel(saveFile,filePath, imgType, start, false);
    }

    /**
     *  将pdf拆装成图片，图片名称默认为pdf下标,使用pdf进行上传
     * @param filePath pdf 路径
     * @param saveFile  pdf保存路径
     * @param imgType   图片类型
     * @param start 起始页码
     * @param isFtp 是否使用ftp
     * @return  返回最后结束页码
     * @throws IOException
     */
    public static Integer PDF2Img(String filePath,String saveFile,String imgType,Integer start,boolean isFtp){
        if(null==start){
            start = 0;
        }
        return isFtpModel(saveFile,filePath, imgType, start, isFtp);
    }

    /**
     * 是否使用ftp模式
     * @param saveFile
     * @param filePath
     * @param imgType
     * @param start
     * @throws IOException
     */
    protected static Integer isFtpModel(String saveFile,String filePath,String imgType,Integer start,boolean isFtp){
        PDDocument pdf = null;
        try {
            pdf = PDDocument.load(new File(filePath));
            PDFRenderer pdfRenderer = new PDFRenderer(pdf);
            PDPageTree pageTree = pdf.getPages();
            int pageCounter = 0;
            for(PDPage page : pageTree){
                float scale = 1.0f;
                //原比例输出
                BufferedImage bim = pdfRenderer.renderImage(pageCounter,scale, ImageType.RGB);
                String fileName = createImgName(start)+"."+imgType;
                if(!isFtp){
                    Iterator<ImageWriter> it = ImageIO.getImageWritersBySuffix(imgType);
                    ImageWriter writer = (ImageWriter) it.next();
                    //写出到文件
                    ImageOutputStream imageout = ImageIO.createImageOutputStream(new FileOutputStream(saveFile+fileName));
                    writer.setOutput(imageout);
                    writer.write(new IIOImage(bim, null, null));
                }else{
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    ImageIO.write(bim, imgType, os);
                    InputStream is = new ByteArrayInputStream(os.toByteArray());
                    FTPClient ftpClient = FTPUtils.getFTPClient();
                    FTPUtils.uploadFile(ftpClient,saveFile, fileName,is);
                }
                //增加下标志
                pageCounter++;
                //页码标记
                start++;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            closePdf(pdf);
        }
        return start;
    }

    protected static void closePdf(PDDocument pdf){
        if(pdf!=null){
            try {
                pdf.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     *  生成6位长度的图片名称
     * @param index
     * @return
     */
    protected static String createImgName(int index) {
        String maxxh = "";
        if (index <= 9) {
            maxxh = "00000" + index;
        } else if (index >= 10 && index <= 99) {
            maxxh = "0000" + index;
        } else if (index >= 100 && index <= 999) {
            maxxh = "000" + index;
        } else if (index >= 1000 && index <= 9999) {
            maxxh = "00" + index;
        } else if (index >= 10000 && index <= 99999) {
            maxxh = "0" + index;
        } else if (index >= 100000 && index <= 999999) {
            maxxh = "" + index;
        }
        return maxxh;
    }
}
